<template>
    <div class="sparkline">
        <svg ref="sparkline" :width="width" :height="height" :stroke-width="strokeWidth" :stroke="strokeColor" :fill="fillColor" />
        <span v-if="tooltip" v-show="tip.show" class="tooltip" :style="[`left: ${tip.left}px`, `top: ${tip.top}px`]">{{ tip.content }}</span>
    </div>
</template>

<script>
import sparkline from '@fnando/sparkline'

export default {
    name: 'Sparkline',
    props: {
        value: {
            type: Array,
            require: true
        },
        width: {
            type: Number,
            default: 100
        },
        height: {
            type: Number,
            default: 30
        },
        strokeWidth: {
            type: Number,
            default: 3
        },
        strokeColor: {
            type: String,
            default: '#dc2b33'
        },
        fillColor: {
            type: String,
            default: 'transparent'
        },
        cursorColor: {
            type: String,
            default: '#dc2b33'
        },
        spotColor: {
            type: String,
            default: '#dc2b33'
        },
        tooltip: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            tip: {
                show: false,
                content: '',
                top: 0,
                left: 0
            }
        }
    },
    mounted() {
        sparkline(this.$refs.sparkline, this.value, this.tooltip && {
            onmousemove: (event, datapoint) => {
                this.tip.show = true
                this.tip.content = datapoint.tooltip
                this.tip.top = event.offsetY
                this.tip.left = event.offsetX + 20
            },
            onmouseout: () => {
                this.tip.show = false
            }
        })
    }
}
</script>

<style lang="scss" scoped>
.sparkline {
    position: relative;
    :deep(.sparkline--cursor) {
        stroke: v-bind('cursorColor');
    }
    :deep(.sparkline--spot) {
        fill: v-bind('spotColor');
        stroke: v-bind('spotColor');
    }
    .tooltip {
        position: absolute;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        padding: 2px 5px;
        font-size: 12px;
        white-space: nowrap;
        z-index: 9999;
    }
}
</style>
